<script setup>
import { ref, reactive, onMounted, watch, nextTick, h } from 'vue';
import { unitApi as MainApi, unitById as MainById } from '@T2/service/api.ts';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useIuserInfoStore, useCurrentWatchStore } from '@T2/store/users.ts';
import Position from './pages/position.vue';
import UploadAttachment from '@T2/components/uploadAttachment/index.vue';
import TreePosition from '@T2/views/Project/Manage/components/tree/position.vue';
import SelectPosition from '@T2/views/Project/Manage/components/select/position.vue';
import dayjs from 'dayjs';

const currentWatchStore = useCurrentWatchStore();
const { curProject } = currentWatchStore;
const iuserInfoStore = useIuserInfoStore();
const { getHandleRight } = iuserInfoStore;
const RIGHT = getHandleRight(['355', '356', '357', '358']);

onMounted(() => {
  GetMainTable();
});
const MainTable = reactive({
  data: [],
  total: 0,
  positionList: [],
});
const Filter = reactive({
  page: 1,
  pagesize: 30,
  ordering: '-create_time',
  year: null,
  search: '',
  wz: '',
  positionsub: null,
});
watch(() => ({...Filter}), (nv, ov) => {
  if (nv.page === 1 || nv.page !== ov.page) {
    GetMainTable();
  } else {
    Filter.page = 1;
  }
});
const positionsLoad = (positionList) => {
  MainTable.positionList = positionList;
}
const positionFormatter = (row) => {
  return MainTable.positionList.find(i => i.id === row.positon)?.name || row.positon;
}
const positionChange = (data, node) => {
  Filter.positionsub = node.data.id || null;
}
const GetMainTable = () => {
  MainApi({
    method: 'get',
    params: {
      ...Filter,
    }
  }).then(res => {
    MainTable.data = res?.results || [];
    MainTable.total = res?.count || 0;
  });
}
/* 新增编辑 */
const MainPopup = reactive({
  visible: false,
  type: '新增',
});
const MainForm = reactive({
  model: {},
  files_json: [],
  files_updateTimes: 0,
});
const MainFormRef = ref(null);
const handleMainAdd = (isAble = false) => {
  if (!isAble) {
    return;
  }
  MainPopup.visible = true;
  MainPopup.type = '新增';
  MainForm.model = {
    _year: dayjs().format('YYYY'),
    files: [],
  };
  MainForm.files_json = [];
  MainForm.files_updateTimes++;
  nextTick(() => {
    MainFormRef.value.clearValidate();
  });
}
const handleMainEdit = (isAble = false, row) => {
  if (!isAble) {
    return;
  }
  MainPopup.visible = true;
  MainPopup.type = '编辑';
  MainForm.model = {
    id: row.id,
    name: row.name,
    code: row.code,
    x: row.x,
    y: row.y,
    addr: row.addr,
    fzr: row.fzr,
    phone: row.phone,
    wz: row.wz,
    files: row.files,
    positon: row.positon,
    _year: '' + row.year, //数字转字符串，使用日历
  };
  MainForm.files_json = row.files_json || [];
  MainForm.files_updateTimes++;
  nextTick(() => {
    MainFormRef.value.clearValidate();
  });
}
const handleMainSubmit = () => {
  MainFormRef.value.validate((valid) => {
    if (valid) {
      MainPopup.visible = false;
      if (MainPopup.type === '新增') {
        AddMain();
      } else if (MainPopup.type === '编辑') {
        EditMain();
      }
    }
  });
}
const AddMain = () => {
  MainForm.model.year = +MainForm.model._year;
  delete MainForm.model._year;
  MainApi({
    method: 'post',
    data: {
      ...MainForm.model,
      project: curProject.id,
    }
  }).then(res => {
    ElMessage.success('新增成功');
    GetMainTable();
  });
}
const EditMain = () => {
  MainForm.model.year = +MainForm.model._year;
  delete MainForm.model._year;
  MainById({
    method: 'patch',
    id: MainForm.model.id,
    data: {
      ...MainForm.model,
    }
  }).then(res => {
    ElMessage.success('编辑成功');
    GetMainTable();
  });
}
const handleMainDelete = (isAble = false, row) => {
  if (!isAble) {
    return;
  }
  ElMessageBox.confirm('', {
    message: h('div', null,[
      h('p',{ style:'font-size:16px;color: #4C4C4C;font-weight:500;'}, `您是否要删除 ${ row.name }？`),
    ]),
    type: 'warning',
    confirmButtonText: '确认',
  }).then(() => {
    MainById({
      method: 'delete',
      id: row.id,
    }).then(res => {
      ElMessage.success('删除成功');
      GetMainTable();
    });
  }).catch(() => {
    ElMessage.info('已取消');
  });
}
/* 选择所属站点 */
const handlePositionSelectChange = (data, node) => {
  MainForm.model.positon = data?.id || null;
}
const positionSelectClear = () => {
  MainForm.model.positon = null;
}
/* 选择年份 */
const NowYear = new Date().getFullYear();
const disableYear = (time) => {
  let year = time.getFullYear();
  return year > NowYear || year < NowYear - 100;
}
/* 上传资料 */
const filesChange = (files) => {
  MainForm.model.files = files;
}


/* 详情 */
const detail = reactive({
  visible: false,
  data: {},
});
const showDetail = (row) => {
  detail.visible = true;
  detail.data = {
    id: row.id,
    name: row.name,
    code: row.code,
    x: row.x,
    y: row.y,
    addr: row.addr,
    fzr: row.fzr,
    phone: row.phone,
    wz: row.wz,
    files_json: row.files_json,
    year: row.year,
  };
}

/* 管理区域跳转 */
const posPage = ref(false);
const goToPosition = (isAble = false) => {
  if (!isAble) {
    return;
  }
  posPage.value = true;
}
</script>

<template>
  <div class="view flex" v-if="!posPage">
    <div class="position flex-column">
      <el-button style="margin-left: auto;" link type="primary" @click="goToPosition(RIGHT['355'])" :disabled="!RIGHT['355']">
        区域管理
      </el-button>
      <TreePosition @current-change="positionChange" @positions-load="positionsLoad" />
    </div>
    <div class="unit-box">
      <div class="flex-column mainCard">
        <el-form label-width="120px" class="flex t_form">
          <el-form-item label="改造年份：">
            <el-date-picker
              v-model="Filter.year"
              type="year"
              placeholder="选择年份"
              format="YYYY"
              value-format="YYYY"
              :disabled-date="disableYear"
            />
          </el-form-item>
          <el-form-item label="站点类型：">
            <el-input v-model="Filter.wz" clearable></el-input>
          </el-form-item>
          <el-form-item label="排序依据：">
            <el-select v-model="Filter.ordering" clearable >
              <el-option value="-create_time" label="按创建时间倒序"></el-option>
              <el-option value="create_time" label="按创建时间正序"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="名称查询：">
            <el-input v-model="Filter.search" clearable></el-input>
          </el-form-item>
          <div class="flex r_btn">
            <el-button type="primary" @click="handleMainAdd(RIGHT['356'])" :disabled="!RIGHT['356']">新增</el-button>
          </div>
        </el-form>
        <el-table :data="MainTable.data" scrollbar-always-on>
          <el-table-column label="站点编号" prop="code" min-width="100px" fixed="left"></el-table-column>
          <el-table-column label="站点名称" prop="name" min-width="210px" fixed="left" show-overflow-tooltip></el-table-column>
          <el-table-column label="站点区域" prop="positon" :formatter="positionFormatter" min-width="140px"></el-table-column>
          <el-table-column label="站点地址" prop="addr" min-width="140px"></el-table-column>
          <el-table-column label="经度" prop="x" min-width="130px"></el-table-column>
          <el-table-column label="纬度" prop="y" min-width="130px"></el-table-column>
          <el-table-column label="类型" prop="wz" min-width="100px"></el-table-column>
          <el-table-column label="建设年份" prop="year" min-width="100px"></el-table-column>
          <el-table-column label="操作" fixed="right" min-width="160px">
            <template #default="scope">
              <el-button link type="primary" @click="handleMainEdit(RIGHT['357'], scope.row)" :disabled="!RIGHT['357']">
                编辑
              </el-button>
              <el-button link type="primary" @click="showDetail(scope.row)">
                详情
              </el-button>
              <el-button link type="danger" @click="handleMainDelete(RIGHT['358'], scope.row)" :disabled="!RIGHT['358']">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          layout="->, total, prev, pager, next, sizes"
          background
          :page-sizes="[10, 20, 30, 50, 100]"
          :pager-count="5"
          v-model:currentPage="Filter.page"
          v-model:page-size="Filter.pagesize"
          :total="MainTable.total"
        />
      </div>
    </div>
  </div>
  
  <Position @exit-position="() => posPage = false" v-else />
  
  <!-- 新增编辑 -->
  <el-dialog width="500px" :title="MainPopup.type + '站点'" v-model="MainPopup.visible">
    <el-form
      ref="MainFormRef"
      :model="MainForm.model"
      label-width="120px"
    >
      <el-form-item prop="positon" label="所属区域：" :rules="[{required: true, message: '不能为空', trigger: 'change'},]">
        <SelectPosition
          :positon="MainForm.model.positon"
          @current-change="handlePositionSelectChange"
          @clear="positionSelectClear"
        />
      </el-form-item>
      <el-form-item prop="code" label="站点位号：" :rules="[{required: true, message: '不能为空', trigger: 'blur'},]">
        <el-input v-model="MainForm.model.code"></el-input>
      </el-form-item>
      <el-form-item prop="name" label="站点名称：" :rules="[{required: true, message: '不能为空', trigger: 'blur'},]">
        <el-input v-model="MainForm.model.name"></el-input>
      </el-form-item>
      <el-form-item prop="addr" label="地址：">
        <el-input v-model="MainForm.model.addr"></el-input>
      </el-form-item>
      <el-form-item prop="x" label="经度：" :rules="[{required: true, message: '不能为空', trigger: 'blur'},]">
        <el-input v-model="MainForm.model.x"></el-input>
      </el-form-item>
      <el-form-item prop="y" label="纬度：" :rules="[{required: true, message: '不能为空', trigger: 'blur'},]">
        <el-input v-model="MainForm.model.y"></el-input>
      </el-form-item>
      <el-form-item prop="_year" label="建设年份：">
        <el-date-picker
          v-model="MainForm.model._year"
          type="year"
          placeholder="选择年份"
          format="YYYY"
          value-format="YYYY"
          :clearable="false"
          :disabled-date="disableYear"
        />
      </el-form-item>
      <el-form-item prop="wz" label="类型：">
        <el-input v-model="MainForm.model.wz"></el-input>
      </el-form-item>
      <!-- <el-form-item prop="fzr" label="站点负责人：">
        <el-input v-model="MainForm.model.fzr"></el-input>
      </el-form-item>
      <el-form-item prop="phone" label="联系电话：">
        <el-input v-model="MainForm.model.phone"></el-input>
      </el-form-item> -->
      <el-form-item prop="files" label="竣工资料：">
        <UploadAttachment
          :fj_json="MainForm.files_json"
          :updateTimes="MainForm.files_updateTimes"
          :maxSizeMB="20"
          @files-change="filesChange"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="MainPopup.visible = false">取 消</el-button>
        <el-button type="primary" @click="handleMainSubmit()">确 定</el-button>
      </span>
    </template>
  </el-dialog>
  
  <!-- 详情 -->
  <el-dialog width="500px" title="站点详情" v-model="detail.visible">
    <el-form :model="detail.data" label-width="120px">
      <el-form-item label="站点编号：">{{ detail.data.code }}</el-form-item>
      <el-form-item label="站点名称：">{{ detail.data.name }}</el-form-item>
      <el-form-item label="地址：">{{ detail.data.addr }}</el-form-item>
      <el-form-item label="经纬度：">{{ detail.data.x }}，{{ detail.data.y }}</el-form-item>
      <el-form-item label="改造年份：">{{ detail.data.year }}</el-form-item>
      <el-form-item label="类型：">{{ detail.data.wz }}</el-form-item>
      <el-form-item label="站点负责人：">{{ detail.data.fzr }}</el-form-item>
      <el-form-item label="联系电话：">{{ detail.data.phone }}</el-form-item>
      <el-form-item label="竣工资料：">
        <div class="detail-files flex-column">
          <a :href="`${ api + item.file_url }`" v-for="item in detail.data.files_json" target="_blank" ><el-icon><Link /></el-icon>{{ item.name}}</a>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="detail.visible = false">关 闭</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
@use '@T2/styles/normal.scss';
.view {
  width: 100%;
  height: 100%;
}
.position {
  width: 220px;
  height: calc(100% - 20px);
  background: #FFFFFF;
  box-shadow: 0px 0px 2px 0px rgba(0,0,0,0.15);
  border-radius: 10px;
  margin: 10px;
  padding: 20px;
}
.unit-box {
  flex: 1;
  overflow: hidden;
  position: relative;
}
.detail-files a {
  display: flex;
  align-items: center;
  gap: 10px;
}
</style>